package com.orange.cetback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.orange.cetback.common.context.BaseContext;
import com.orange.cetback.common.enums.WordLearningStage;
import com.orange.cetback.common.utils.AliOssUtil;
import com.orange.cetback.common.vo.PageResult;
import com.orange.cetback.pojo.dto.QueryWordDTO;
import com.orange.cetback.pojo.dto.UnreviewedWordsDTO;
import com.orange.cetback.pojo.dto.WordDTO;
import com.orange.cetback.pojo.entity.Cet4Word;
import com.orange.cetback.mapper.Cet4WordMapper;
import com.orange.cetback.pojo.vo.StudyWordVO;
import com.orange.cetback.service.Cet4WordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenenjun
 * @since 2025-02-18
 */
@Service
public class Cet4WordServiceImpl extends ServiceImpl<Cet4WordMapper, Cet4Word> implements Cet4WordService {

    @Autowired
    private AliOssUtil aliOssUtil;

    //分页查询单词
    @Override
    public PageResult<Cet4Word> pageQuery(QueryWordDTO queryWordDTO) {
        Page<Cet4Word> page = new Page<>(queryWordDTO.getPageNum(), queryWordDTO.getPageSize());
        LambdaQueryWrapper<Cet4Word> queryWrapper = new LambdaQueryWrapper<>();
        if(WordLearningStage.getStageName(queryWordDTO.getStage()).equals(WordLearningStage.UN_LEARNING.getStageName())){
            queryWrapper.notExists(
                    "SELECT 1 FROM user_word_review r " +
                            "WHERE r.user_id = {0} AND r.word_id = cet4_word.id",
                    BaseContext.getCurrentId()
            );
        } else if (WordLearningStage.getStageName(queryWordDTO.getStage()).equals(WordLearningStage.REVIEW.getStageName())) {
            queryWrapper.exists(
                    "SELECT 1 FROM user_word_review r " +
                            "WHERE r.user_id = {0} AND r.word_id = cet4_word.id",
                    BaseContext.getCurrentId()
            );
        }
        Page<Cet4Word> wordPage = this.page(page, queryWrapper);
        return  new PageResult<>(wordPage.getTotal(), wordPage.getRecords());
    }

    @Override
    public PageResult<Cet4Word> pageQueryWord(WordDTO wordDTO) {
        Page<Cet4Word> page = new Page<>(wordDTO.getPageNum(), wordDTO.getPageSize());
        LambdaQueryWrapper<Cet4Word> queryWrapper = new LambdaQueryWrapper<>();
        if (wordDTO.getWordType() != null && !wordDTO.getWordType().equals("")){
            queryWrapper.eq(Cet4Word::getWordType, wordDTO.getWordType());
        }
        queryWrapper.like(Cet4Word::getCet4Word, wordDTO.getWord());
        this.baseMapper.selectPage(page, queryWrapper);
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    @Override
    public PageResult<StudyWordVO> getUnreviewedWords(UnreviewedWordsDTO unreviewedWordsDTO) {
        // 第一步：创建分页对象
        Page<Cet4Word> page = new Page<>(unreviewedWordsDTO.getPageNum(), unreviewedWordsDTO.getPageSize());
        // 第二步：查询未背诵过的单词（分页）
        this.baseMapper.selectUnreviewedWordsPage(page,BaseContext.getCurrentId());
        // 第三步：封装结果到 StudyWordVO
        List<StudyWordVO> studyWordVOList = new ArrayList<>();
        for (Cet4Word word : page.getRecords()) {
            StudyWordVO studyWordVO = new StudyWordVO();
            BeanUtils.copyProperties(word, studyWordVO);
            // 查找前缀相似的单词
            String wordPrefix = word.getCet4Word().substring(0, Math.min(3, word.getCet4Word().length()));
            List<Cet4Word> similarWords = selectSimilarWordsByPrefix(wordPrefix);
            studyWordVO.setSimilarWords(similarWords);
            studyWordVOList.add(studyWordVO);
        }

        return new PageResult<>(page.getTotal(), studyWordVOList);
    }



    public List<Cet4Word> selectSimilarWordsByPrefix(String prefix){
        LambdaQueryWrapper<Cet4Word> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Cet4Word::getCet4Word, prefix);
        wrapper.last("LIMIT 4");
        return this.baseMapper.selectList(wrapper);
    }


    @Override
    public void batchUpdateAudioUrls(Integer startId, Integer endId) {
        // 1. 查询ID范围内的单词
        List<Cet4Word> words = this.list(new LambdaQueryWrapper<Cet4Word>()
                .between(Cet4Word::getId, startId, endId));
        // 2. 遍历处理每个单词
        words.forEach(word -> {
            try {
                // 美音处理
                String usAudioUrl = downloadAndUploadAudio(word.getCet4Word(), 0, "us");
                // 英音处理
                String ukAudioUrl = downloadAndUploadAudio(word.getCet4Word(), 1, "uk");
                word.setUkAudioUrl(ukAudioUrl);
                this.updateById(word);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }



    private String downloadAndUploadAudio(String word, int type, String prefix) throws Exception {
        URL url = new URL("http://dict.youdao.com/dictvoice?type=" + type + "&audio=" + word);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        String ossUrl = aliOssUtil.upload(inputStream.readAllBytes(), "audio/" + prefix + "/" + word + ".mpga");
        inputStream.close();
        connection.disconnect();
        return ossUrl;
    }
}
